package com.xm.shop.service.impl;

import com.xm.shop.exceptions.ShopException;
import com.xm.shop.mapper.UserMapper;
import com.xm.shop.pojo.entity.User;
import com.xm.shop.pojo.qo.UserLoginQO;
import com.xm.shop.service.UserService;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

@Service
public class UserServiceImpl implements UserService {
    private Logger logger = LoggerFactory.getLogger(UserServiceImpl.class);

    @Autowired
    private UserMapper userMapper;

    public User getById(Long userId) {
        User user = userMapper.selectById(userId);
        if (null == user) {
            //查询用户不存在，抛出异常
            //todo 打印 warn日志
            logger.warn("getById user not exist [userId:{}]", userId);
            throw new RuntimeException("用户不存在");
        }
        return user;
    }

    @Override
    public User login(UserLoginQO qo) {
        //根据用户名查询数据库
        User dbUser = userMapper.selectByUserName(qo.getUserName());

        if (null == dbUser) {
            //用戶不存在
            throw new ShopException("用戶不存在");
        }
        //判断密码是否正确
        if (!dbUser.getPassword().equals(qo.getPassword())) {
            //密码错误
            throw new ShopException("密码错误");
        }
        //去除安全隐私信息
        dbUser.setPassword(null);
        return dbUser;
    }


    @Override
    public int insertUser(User user) {

        //根据用户名查询数据库
        User dbUser = userMapper.selectByUserName(user.getUserName());

        if (dbUser!=null&&dbUser.getUserName().equals(user.getUserName())) {
            //用戶已存在
            System.out.println("1111");
            throw new ShopException("用户已存在");
        }


        int result = userMapper.insertUser(user);
        return result;
    }
}
